#include "pca.h"

volatile unsigned long oldData;
volatile unsigned long newData;
volatile unsigned long highLevelTime;
volatile unsigned long lowLevelTime;

volatile unsigned long IColdData;
volatile unsigned long ICnewData;
volatile unsigned char overflow_num1;
volatile unsigned char overflow_num2;
volatile unsigned long InputCapture;

volatile unsigned char flag1;
volatile unsigned char flag2;


void pca_init(void)
{
    CCON = 0X00;
    CMOD = 0X01;

    CL = 0;
    CH = 0;

	//8位PWM输出
		CCAPM1 = 0x42;
		PCA_PWM1 = 0X00;
		CCAP1H = 0;
		CCAP1L = 1;
	
	//脉冲宽度捕获
		CCAPM2 = 0X21;
		CCAP2H = 0;
		CCAP2L = 0;
		
	//频率测量
		CCAPM0 = 0X21;
		CCAP0H = 0;
		CCAP0L = 0;
		
		oldData = 0;
		newData = 0;
		IColdData = 0;
		ICnewData = 0;
		
		highLevelTime = 0;
		lowLevelTime = 0;
		InputCapture = 0;
		
		overflow_num1 = 0;
		overflow_num2 = 0;
	
		flag1 = 0;
		flag2 = 0;
		
    CR = 1;
}

void SetPwmDuty(uint8_t duty)
{
	CCAP1H = duty*51/20;
	if (CCAP1H == 0)
		CCAP1H = 1;
}

void PCA_Isr() interrupt 7
{
		if(CF)
		{
			CF = 0;
			overflow_num1++;
			overflow_num2++;
			
			if(++flag1 >= 10)
			{
				InputCapture = 0;
			}
			if(++flag2 >= 10)
			{
				lowLevelTime = 0;
				highLevelTime = 0;
			}
		}
    if(CCF0){
				CCF0 = 0;
				flag1 = 0;
				IColdData = ICnewData;
				((unsigned char *)&ICnewData)[3] = CCAP0L;
				((unsigned char *)&ICnewData)[2] = CCAP0H;
				((unsigned char *)&ICnewData)[1] = overflow_num1;
				((unsigned char *)&ICnewData)[0] = 0;
				InputCapture = ICnewData - IColdData;
		}
    if(CCF2){
        CCF2 = 0;
				flag2 = 0;
				if(CCAPM2 == 0X21)
				{
					CCAPM2 = 0X11;
					
					oldData = newData;
					((unsigned char *)&newData)[3] = CCAP2L;
					((unsigned char *)&newData)[2] = CCAP2H;
					((unsigned char *)&newData)[1] = overflow_num2;
					((unsigned char *)&newData)[0] = 0;
					lowLevelTime = newData - oldData;
				}
				else if(CCAPM2 == 0X11)
				{
					CCAPM2 = 0X21;
					
					oldData = newData;
					((unsigned char *)&newData)[3] = CCAP2L;
					((unsigned char *)&newData)[2] = CCAP2H;
					((unsigned char *)&newData)[1] = overflow_num2;
					((unsigned char *)&newData)[0] = 0;
					highLevelTime = newData - oldData;
				}
    }
}














